/*
 * shared_memory.hpp
 *
 *  Created on: 2023年5月17日
 *      Author: Dylan.Gao
 */

#ifndef _DM_OS_SHARED_MEMORY_HPP_
#define _DM_OS_SHARED_MEMORY_HPP_

#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>

namespace dm{
namespace os{

/**
 * 构造非限制的权限
 */
class CUnrestrictedPermissions:public boost::interprocess::permissions{
public:
	CUnrestrictedPermissions():boost::interprocess::permissions(){
		set_unrestricted();
	}
};

/**
 * 获取共享内存的封装
 * @param name
 * @param p
 * @param size
 * @param ptr
 * @return
 */
inline boost::interprocess::mapped_region* getSharedMemory( const char* name,const boost::interprocess::permissions& p,const size_t& size,volatile void** ptr=nullptr ){
	boost::interprocess::shared_memory_object shm(boost::interprocess::open_or_create,name,boost::interprocess::read_write,p);
	shm.truncate(size);

	boost::interprocess::mapped_region* mr = new boost::interprocess::mapped_region(shm,boost::interprocess::read_write);
	if( ptr )
		*ptr = mr->get_address();

	return mr;
}

/**
 * 获取共享内存的封装
 * @tparam T
 * @param name
 * @param p
 * @return
 */
template<typename T>
inline boost::interprocess::mapped_region* getSharedMemory( const char* name,const boost::interprocess::permissions& p,volatile T** ptr=NULL ){
	return getSharedMemory(name, p, sizeof(T), (volatile void**)ptr);
}

}
}



#endif /* _DM_OS_SHARED_MEMORY_HPP_ */
